import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';
import 'package:permission_handler/permission_handler.dart';

class AppPermissionSetting extends StatefulWidget {
  const AppPermissionSetting({super.key});

  @override
  State<AppPermissionSetting> createState() => _AppPermissionSettingState();
}

class _AppPermissionSettingState extends State<AppPermissionSetting> {
  PermissionStatus? _cameraPermissionStatus;
  PermissionStatus? _locationWhenInUsePermissionStatus;

  @override
  void initState() {
    super.initState();

    _getCurrentPermissionStatus();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: _buildBody());
  }

  /// Builds main body.
  Widget _buildBody() {
    return ListView(
      children: [
        Container(
          margin: const EdgeInsets.fromLTRB(15.0, 80.0, 15.0, 0.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text('权限设置', style: TextStyle(fontSize: 30.0)),
              const Text(
                '为正常使用请点击开启以下权限',
                style: TextStyle(fontSize: 18.0, color: Color(0xFF666666)),
              ),
              const SizedBox(height: 50),
              ListTile(
                contentPadding: const EdgeInsets.all(0.0),
                leading: Container(
                  padding: const EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    color: Colors.grey[200],
                    borderRadius: BorderRadius.circular(6.0),
                  ),
                  child: Icon(
                    Icons.local_see,
                    size: 45.0,
                    color: _getPermissionStatusColor(_cameraPermissionStatus),
                  ),
                ),
                title: const Text('访问摄像头'),
                subtitle: const Text('上传头像'),
                onTap: () async {
                  _cameraPermissionStatus = await Permission.camera.request();

                  switch (_cameraPermissionStatus) {
                    case PermissionStatus.granted:
                      showToast('已授权访问摄像头权限');
                      break;
                    case PermissionStatus.denied:
                      showToast('已拒绝访问摄像头权限，请尝试重新授权。');
                      break;
                    case PermissionStatus.permanentlyDenied:
                      showToast('访问摄像头权限已被永久禁止，请在系统设置界面修改。');
                      break;
                    default:
                  }

                  if (mounted) {
                    setState(() {});
                  }
                },
              ),
              const SizedBox(height: 20),
              ListTile(
                contentPadding: const EdgeInsets.all(0.0),
                leading: Container(
                  padding: const EdgeInsets.all(5.0),
                  decoration: BoxDecoration(
                    color: Colors.grey[200],
                    borderRadius: BorderRadius.circular(6.0),
                  ),
                  child: Icon(
                    Icons.room,
                    size: 45.0,
                    color: _getPermissionStatusColor(
                      _locationWhenInUsePermissionStatus,
                    ),
                  ),
                ),
                title: const Text('定位'),
                subtitle: const Text('选择位置需要该权限'),
                onTap: () async {
                  _locationWhenInUsePermissionStatus = await Permission
                      .locationWhenInUse
                      .request();

                  switch (_locationWhenInUsePermissionStatus) {
                    case PermissionStatus.granted:
                      showToast('已授权定位权限');
                      break;
                    case PermissionStatus.denied:
                      showToast('已拒绝定位权限，请尝试重新授权。');
                      break;
                    case PermissionStatus.permanentlyDenied:
                      showToast('定位权限已被永久禁止，请在系统设置界面修改。');
                      break;
                    default:
                  }

                  if (mounted) {
                    setState(() {});
                  }
                },
              ),
              const SizedBox(height: 20),
              Container(
                margin: const EdgeInsets.symmetric(vertical: 60.0),
                height: 42.0,
                width: double.infinity,
                child: OutlinedButton(
                  style: ButtonStyle(
                    foregroundColor: WidgetStateProperty.all<Color>(
                      Colors.grey,
                    ),
                  ),
                  child: Text(
                    _cameraPermissionStatus?.isGranted == true &&
                            _locationWhenInUsePermissionStatus?.isGranted ==
                                true
                        ? '完成'
                        : '稍后设置',
                  ),
                  onPressed: () => NavigatorHelper.pop(context),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// Gets current app required permission status.
  Future<void> _getCurrentPermissionStatus() async {
    _cameraPermissionStatus = await Permission.camera.status;

    _locationWhenInUsePermissionStatus =
        await Permission.locationWhenInUse.status;

    // Triggers UI build.
    if (mounted) {
      setState(() {});
    }
  }

  Color _getPermissionStatusColor(PermissionStatus? permissionStatus) {
    switch (permissionStatus) {
      case PermissionStatus.denied:
        return Colors.red;
      case PermissionStatus.granted:
        return const Color(0xFF8BC34A);
      case PermissionStatus.limited:
        return Colors.red;
      case PermissionStatus.restricted:
        return Colors.red;
      case PermissionStatus.permanentlyDenied:
        return Colors.red;
      default:
        return Colors.grey;
    }
  }
}
